const Service = require('egg').Service,
  _ = require('lodash');
Xlsx = require('xlsx');

class SmsService extends Service {

  async template() {
    const info = this.app.config.sms.options;

    const arr = [];
    Object.keys(info).map(m => {
      let signTitle = '';
      let product_type = '';
      if (m === 'ykqj') {
        signTitle = '【一刻千金】';
        product_type = 'YKQJ';
      }
      if (m === 'qyl') {
        signTitle = '【钱有路】';
        product_type = 'QYL';
      }
      if (m === 'qsjs') {
        signTitle = '【钱是金生】';
        product_type = 'QSJS';
      }

      Object.keys(info[m].templates).map(n => {
        const tempObj = {};
        tempObj.signatureid = info[m].signatureid; // 签名
        tempObj.product_type = product_type; // 产品类型
        tempObj.signTitle = signTitle;
        // 内容
        if (n === 'cash') {
          tempObj.award_type = '1';
          tempObj.templateid = info[m].templates[n]; // 模板id
          tempObj.title = '现金奖品发放'; // 标题
          tempObj.content = signTitle + '用户您好，恭喜您获得奖励xxxxx元，已支付到您的银行卡，请注意查收；退订回复TD'; // 内容
        }

        // 内容
        if (n === 'gift') {
          tempObj.award_type = '2';
          tempObj.templateid = info[m].templates[n]; // 模板id
          tempObj.title = '实物奖品发放'; // 标题
          tempObj.content = signTitle + '用户您好，恭喜您获得奖励xxxxx已通过快递发出，请注意查收；退订回复TD'; // 内容
        }

        // 内容
        if (n === 'virtual') {
          tempObj.award_type = '3';
          tempObj.templateid = info[m].templates[n]; // 模板id
          tempObj.title = '虚拟奖品发放'; // 标题
          tempObj.content = signTitle + '用户您好，恭喜您获得奖励xxxxx兑换码为xxxx，请点击 http//sddfggg 进行兑换；退订回复TD'; // 内容
        }

        arr.push(tempObj);
      });
    });

    return arr;
  }

  async xlsxFile(file, array) {
    const buffer = await this.service.file.streamToBuffer(file);
    const workbook = Xlsx.read(buffer, {type: "buffer"});
    const SheetNames = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[SheetNames];
    const jsonList = Xlsx.utils.sheet_to_json(worksheet);
    jsonList.map(item => {
      for(let key of array){
        if(!item[key]){
          throw new Error(`.xlsx文件属性不完整，请包含 "${array}" 等属性！`);
        }
      }
    });
    return jsonList;
  }
}

module.exports = SmsService;
